package com.example.park_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.park_management.common.PageParam;
import com.example.park_management.common.Result;
import com.example.park_management.domain.Buildings;
import com.example.park_management.domain.ParkingSpaces;
import com.example.park_management.service.ParkingSpacesService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping("/parkingSpaces")
public class ParkingSpacesController {

    @Resource
    ParkingSpacesService parkingSpacesService;

    @PostMapping("/")
    Result add(@RequestBody ParkingSpaces parkingSpaces) {
        try{
            boolean save = parkingSpacesService.save(parkingSpaces);
            return save ? Result.success() : Result.fail();
        }catch (NumberFormatException e) {
            return Result.fail("输入格式异常！");
        }
    }

    @PutMapping("/")
    Result update(@RequestBody ParkingSpaces parkingSpaces) {
        try{
            if (StringUtils.isBlank(parkingSpaces.getSpaceNumber())) {
                return Result.fail("必填属性为空");
            }
            boolean update = parkingSpacesService.updateById(parkingSpaces);
            return update ? Result.success() : Result.fail();
        }catch (NumberFormatException e) {
            return Result.fail("输入格式异常！");
        }
    }

    @DeleteMapping("/{spaceId}")
    Result delete(@PathVariable Integer spaceId) {
        boolean b = parkingSpacesService.removeById(spaceId);
        return b ? Result.success() : Result.fail();
    }

    @PostMapping("/page")
    Result page(@RequestBody PageParam<ParkingSpaces> pageParam) {
        Page<ParkingSpaces> parkingSpacesPage = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());

        QueryWrapper<ParkingSpaces> parkingSpacesQueryWrapper = new QueryWrapper<>();
        if (pageParam.getData() != null){
            if (pageParam.getData().getLicensePlate() != null){
                parkingSpacesQueryWrapper.like("license_plate", pageParam.getData().getLicensePlate());
            }
            if (pageParam.getData().getSpaceNumber() != null){
                parkingSpacesQueryWrapper.like("space_number", pageParam.getData().getSpaceNumber());
            }

            if (pageParam.getData().getStatus() != null && pageParam.getData().getStatus() != -1){
                parkingSpacesQueryWrapper.eq("status", pageParam.getData().getStatus());
            }

        }
        parkingSpacesService.page(parkingSpacesPage,parkingSpacesQueryWrapper);
//        parkingSpacesService.page(parkingSpacesPage);
        return Result.success(parkingSpacesPage.getRecords(),parkingSpacesPage.getTotal());
    }

}
